package com.gxa.auth;


import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.gxa.common.constant.ScommunityConstant;
import com.gxa.common.utils.*;
import com.gxa.entity.user.SysUser;
import com.gxa.entity.user.User;
import com.gxa.mapper.user.UserMapper;
import com.gxa.service.user.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;


/**
 * 认证
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {
    //    @Autowired
//    private ShiroService shiroService;
    @Resource
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SysUserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//        SysUserEntity user = (SysUserEntity)principals.getPrimaryPrincipal();
//        Long userId = user.getUserId();

        //用户权限列表
//        Set<String> permsSet = shiroService.getUserPermissions(userId);

//        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.setStringPermissions(permsSet);
//        return info;

        System.out.println("------------------OAuth2Realm--授权方法----------------");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
         String token = (String) principals.getPrimaryPrincipal();
        System.out.println(token+"token-------------");
        Set<String> perms = new HashSet<>();
//        if("admin".equals(user.getUserName())){
            perms.add("emp:list");
            perms.add("emp:add");
            perms.add("emp:update");
            perms.add("emp:delete");
//        }else if("zs".equals(user.getUserName())){
//            perms.add("emp:list");
//            perms.add("emp:add");
//            perms.add("emp:update");
//        }else if("ls".equals(user.getUserName())){
//            perms.add("emp:list");
//        }

        info.addStringPermissions(perms);
        System.out.println("授予的权限：--"+perms);
        return info;

    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {



        System.out.println("------------------OAuth2Realm--认证方法----------------");
        // 这里的 token是从 JWTFilter 的 executeLogin 方法传递过来的
        String token = (String) authenticationToken.getCredentials();
        // 1- 从缓存中获得登录时存入的token
        String redisToken = null;
        // 从 redis里获取这个 token
        try {
            // key  为   系统参数 + token
            String key = ScommunityConstant.ZHUIYI_TOKEN +token;
            redisToken = (String) this.redisUtil.get(key);
        }catch (Exception e){
            e.printStackTrace();
        }
        //校验redisToken
        if(StringUtils.isBlank(redisToken)){
            throw new AuthenticationException("token已失效!");
        }

        // 通过token得到 用户名
        String username = JWTUtils.getUsername(token);
        if(StringUtils.isBlank(username)){
            throw new AuthenticationException("token校验不通过!");
        }
        // 得到当前用户
        SysUser user = this.userService.queryByUserName(username);
        if(null == user){
            throw new AuthenticationException("用户名或密码错误!");
        }
        if(ScommunityConstant.ACCOUNT_LOCK.equals(user.getStatus())){
            throw new AuthenticationException("该用户账号被锁定!");
        }

        //也可以增加ip校验
        //HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        //            String ip = IPUtils.getIpAddr(request);
        //            if (!StringUtils.equals(ip, user.getLoginIp())) {
        //                throw new IncorrectCredentialsException("非法使用token");
        //            }
        if(!JWTUtils.verify(token,username,user.getPassword())){
            throw new AuthenticationException("token校验不通过!");
        }
        return new SimpleAuthenticationInfo(token, token, "shiro_realm");

    }
}
